$(document).on('pageinit', function() {
    loadGroups();

});

function openGroupDetail(group_data){
    console.log("Opening group detail with data: " + group_data.id + ", name = " + group_data.name);
    $("#group_detail_id").text(group_data.id);
    $("#group_detail_name").val(group_data.name);

    $( "#group_popup" ).trigger( "create" );
    $( "#group_popup" ).popup( "open" );

}


function loadGroups(){
    console.log( "Loading groups..." );
    $.mobile.loading( 'show', { text: "", textonly: false});

    $.ajax({
        url: "/groups",
        type: "GET",
        success: function(data){
            console.log(data);

            for(var i = 0; i < data.length; i++) {
                var obj = data[i];
                $("#groups_table_body").append(createGroupRow(obj.id, obj.name));
                $('#tr_group_'+obj.id+' td input').button();
            }
            $.mobile.loading( 'hide', { text: "", textonly: false});
            $('#groups_table').table("refresh");

        },
        error: function (error){
            alert("error:" + error);
            $.mobile.loading( 'hide', { text: "", textonly: false});
        }

    });
}


function createGroupRow(id, name){
    return '<tr id="tr_group_'+id+'">' +
            '   <td>'+id+'</td>' +
            '   <td style="width:50%">'+name+'</td>' +
            '   <td><input type="button" data-icon="gear" data-iconpos="notext" data-mini="true" value="Change name"></td>'+
            '   <td><input type="button" data-icon="delete" data-iconpos="notext" data-mini="true" value="Leave group" ></td>'+
            '</tr>';
}
